package com.ywyself.controller.admin;

import com.jfinal.core.ActionKey;
import com.jfinal.upload.UploadFile;
import com.ywyself.common.YsConfig;
import com.ywyself.controller.base.YsController;
import com.ywyself.ext.kit.YsKit;
import com.ywyself.ext.utils.YsDateUtils;
import com.ywyself.ext.utils.YsFileUtils;
import com.ywyself.ext.utils.YsVerifyUtils;

/**
 * 文件上传
 *
 * @author YuWenYue
 * @date 2017-10-10 20:00:43
 */
public class UploadController extends YsController {

    @ActionKey(ADMIN_ROOT + "/upload/image")
    public void image() {
        UploadFile uFile = getFile("image", YsConfig.upload_image);
        if (uFile == null) {
            YsKit.fail().code("400").msg("图片上传失败").render(this);
        } else if (!uFile.getContentType().contains("image")) {
            YsKit.fail().code("300").msg("图片格式不正确").render(this);
        } else {
            String fileName = uFile.getFileName();
            fileName = YsDateUtils.getStr("yyyyMMddHHmmss") + YsVerifyUtils.getVerifyCode()
                    + fileName.substring(fileName.lastIndexOf("."));
            if (YsFileUtils.renameTo(uFile.getFile(), fileName)) {
                YsKit.ok().code("100").msg("上传成功")
                        .set("path", YsConfig.BASE_UPLOAD + YsConfig.upload_image + "/" + fileName).render(this);
            } else {
                YsKit.fail().code("400").msg("上传失败").render(this);
            }
        }
    }
}
